<template>
  <div>
    <div :class="this.$store.getters.avatar ? 'avatarBox avatarBoxShadow' : 'avatarBox avatarBoxBorder'" @click="editCropper()">
      <el-image title="点击修改头像" v-if="this.$store.getters.avatar" class="avatar" :src="this.$store.getters.avatar" fit="cover"></el-image>
      <i v-else class="el-icon-plus avatar-icon"></i>
    </div>
    <my-dialog
      :title="this.$store.getters.avatar ? '修改头像':'添加头像'"
      :width="800"
      :height="400"
      :visible="visible"
      @onClose="closeDialog"
      @onConfirm="uploadImg"
    >
    <div slot="content" style="margin: 0 30px">
      <el-row>
        <el-col :xs="24" :md="12" :style="{height: '350px'}">
          <vue-cropper
            ref="cropper"
            :img="options.img"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            @realTime="realTime"
          />
        </el-col>
        <el-col :xs="24" :md="12" :style="{height: '350px'}">
          <div class="avatar-upload-preview">
            <img v-if="options.img" :src="previews.url" :style="previews.img" />
          </div>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :lg="2" :md="2">
          <el-upload
            action="#"
            :http-request="requestUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
            accept=".png,.jpg,.jpeg,.gif"
          >
            <el-button size="small">
              选择文件
            </el-button>
          </el-upload>
        </el-col>
        <el-col :lg="{span: 1, offset: 2}" :md="2">
          <el-button icon="el-icon-plus" size="small" @click="changeScale(1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :md="2">
          <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :md="2">
          <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :md="2">
          <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()"></el-button>
        </el-col>
      </el-row>
    </div>
    </my-dialog>
  </div>
</template>

<script>
import { VueCropper } from "vue-cropper";
import { editUserAvatarApi } from "@/api/user";
import myDialog from "@/components/MyDialog/index";
export default {
  components: { VueCropper, myDialog },
  // props: {
  //   user: {
  //     type: Object,
  //     required: true
  //   }
  // },
  data() {
    return {
      // 是否显示弹出层
      visible: false,
      // 弹出层标题
      fileName:"",
      previews: {},
      options: {
        img: '', //裁剪图片的地址
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 200, // 默认生成截图框宽度
        autoCropHeight: 200, // 默认生成截图框高度
        fixedBox: true // 固定截图框大小 不允许改变
      }
    };
  },
  methods: {
    // 编辑头像
    editCropper() {
      this.options.img = '';
      // this.previews = {};
      this.visible = true;
    },
    // 覆盖默认的上传行为
    requestUpload() {
    },
    // 向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
    // 图片缩放
    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") === -1) {
        this.$message.error("文件格式错误，请上传类型如：JPG、PNG、GIF后缀的图片！");
        return false;
      }else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.options.img = reader.result;
        }
        this.fileName = file.name;
      }
      return true;
    },
    // 上传图片
    uploadImg() {
      this.$refs.cropper.getCropBlob( async data => {
        if(data.size> 2097152) {
          this.$message.error("请上传大小不超过2M的图片！");
        }
        let formData = new FormData();
        formData.append("avatarFile",data,this.fileName);
        formData.append("id",this.$store.getters.userId);
        formData.append("nowAvatar",this.$store.getters.avatar);
        let res = await editUserAvatarApi(formData);
        if(res&&res.code==200){
          this.$message.success(res.msg);
          this.$store.commit('user/SET_AVATAR', res.data)
          this.options.img = this.$store.getters.avatar
        }
      });
      this.visible = false
    },
    // 实时预览
    realTime(data) {
      this.previews = data;
    },
    // 关闭窗口
    closeDialog() {
      this.visible = false;
      this.options.img = '';
      // this.previews = {};
    }
  }
};
</script>
<style scoped lang="scss">
.avatarBox{
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 130px;
  height: 130px;
  margin: 0 auto 10px auto;
}

.avatarBoxShadow{
  box-shadow: 1px 5px 5px #615151;
  transition: 0.35s;
}

.avatarBoxShadow:hover{
  box-shadow: 2px 7px 8px #887575;
  transition: 0.35s;
}


.avatarBoxBorder {
  border: 2px dashed #d9d9d9;
}

.avatarBoxBorder:hover{
  border-color: #409EFF;
}

.avatarBoxBorder:hover .avatar-icon{
  color: #409EFF;
}

.avatar {
  width: 130px;
  height: 130px;
  display: block;
}

.avatar-icon{
    font-size: 28px;
    font-weight: bold;
    color: #8c939d;
    width: 125px;
    height: 130px;
    line-height: 130px;
    text-align: center;
}

/* image */
.img-circle {
  border-radius: 50%;
}

.img-lg {
  width: 120px;
  height: 120px;
}
.avatar-upload-preview {
  position: absolute;
  top: 50%;
  transform: translate(50%, -50%);
  width: 200px;
  height: 200px;
  border-radius: 50%;
  box-shadow: 0 0 4px #ccc;
  // border: 1px solid #ccc;
  overflow: hidden;
}
</style>
